#!/usr/bin/env bash

# Copyright 2021 Flant JSC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

source /shell_lib.sh

function __config__() {
  cat <<EOF
configVersion: v1
kubernetesCustomResourceConversion:
  - name: alpha1_to_v1
    crdName: yandexinstanceclasses.deckhouse.io
    conversions:
    - fromVersion: deckhouse.io/v1alpha1
      toVersion: deckhouse.io/v1
  - name: v1_to_alpha1
    crdName: yandexinstanceclasses.deckhouse.io
    conversions:
    - fromVersion: deckhouse.io/v1
      toVersion: deckhouse.io/v1alpha1
EOF
}

function __on_conversion::alpha1_to_v1() {
  if converted=$(context::jq -r '.review.request.objects//[] | map(
     if .apiVersion == "deckhouse.io/v1alpha1" then
       .apiVersion = "deckhouse.io/v1" |
       if .spec.networkType then
          .spec.networkType |= if . == "STANDARD" then "Standard" elif . == "SOFTWARE_ACCELERATED" then "SoftwareAccelerated" else . end
       else . end
     else . end
  )'); then
    cat <<EOF >"$CONVERSION_RESPONSE_PATH"
{"convertedObjects": $converted}
EOF
  else
    cat <<EOF >"$CONVERSION_RESPONSE_PATH"
{"failedMessage":"Conversion of yandexinstanceclasses.deckhouse.io failed"}
EOF
  fi
}

function __on_conversion::v1_to_alpha1() {
  if converted=$(context::jq -r '.review.request.objects//[] | map(
     if .apiVersion == "deckhouse.io/v1" then
       .apiVersion = "deckhouse.io/v1alpha1" |
       if .spec.networkType then
          .spec.networkType |= if . == "Standard" then "STANDARD" elif . == "SoftwareAccelerated" then "SOFTWARE_ACCELERATED" else . end
       else . end
     else . end
  )'); then
    cat <<EOF >"$CONVERSION_RESPONSE_PATH"
{"convertedObjects": $converted}
EOF
  else
    cat <<EOF >"$CONVERSION_RESPONSE_PATH"
{"failedMessage":"Conversion of yandexinstanceclasses.deckhouse.io failed"}
EOF
  fi
}

hook::run "$@"
